package com.rainday.jarweb.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import com.rainday.jarweb.initializer.HttpWEBServerInitializer;

public class HttpWEBServer {
	public HttpWEBServer(int port){
		this.port = port;
	}

	private int port;
	public static boolean isSSL;

	public static void setSSL(boolean isSSL)
	{
		HttpWEBServer.isSSL = isSSL;
	}

	public void start() throws Exception
	{
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.childHandler(new HttpWEBServerInitializer())//初始化handler时绑定encoder，decoder这样可以处理http请求，否则是不可以处理http请求的
			.option(ChannelOption.SO_BACKLOG, 128)
			.childOption(ChannelOption.SO_KEEPALIVE, true);
			//绑定端口，同步等待成功
			ChannelFuture cf = b.bind(this.port).sync();
			//等待服务端坚挺端口关闭
			cf.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}
	public static void main(String[] args) throws Exception
	{
		int port = 8080;
		HttpWEBServer server = new HttpWEBServer(port);
		System.out.println("Http Server listening on "+port+" ...");
		server.start();
	}
}